package com.lagou.rpc.boot;

import com.lagou.decoder.RpcDecoder;
import com.lagou.request.RpcRequest;
import com.lagou.rpc.handler.UserServerHandler;
import com.lagou.serializer.JSONSerializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

/**
 * ServerBootStrap
 *
 * @author thresh
 * @since 2021/2/22 20:21
 */
public class ServerBootStrap {

    public static void startServer(String hostName, int port) throws InterruptedException {

        // 创建两个线程池
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        // 创建、配置启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                // 设置通道为nio
                .channel(NioServerSocketChannel.class)
                // 监听channel
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 获取管道对象
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        // 给管道对象设置编码
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()))
                                .addLast(new StringEncoder())
                                // 给管道添加一个自定义处理类
                                .addLast(new UserServerHandler());
                    }
                });

        // 绑定端口，异步
        serverBootstrap.bind(hostName, port).sync();
        System.out.println("服务端启动成功");

    }

}
